package com.nsgf.library.ui.page;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.binding_state.BR;
import com.nsgf.library.data.bean.Shop;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.event.EventMsg;
import com.nsgf.library.ui.adapter.CartAdapter;
import com.nsgf.library.ui.product.ConfirmOrderActivity;
import com.nsgf.library.utils.StringUtil;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.zhht.htzx.R;
import com.zhht.htzx.databinding.ActivityShoppingCartBinding;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class ShoppingCartActivity extends BaseActivity implements CartAdapter.OnCartItemChangeListener {


    private StateHolder mStates;

    private ActivityShoppingCartBinding mBinding;

    private AccountRequester mAccountRequester;

    private CartAdapter adapter;
    private List<Shop.ValidListBean> shops;


    @Override
    protected void initViewModel() {

        mStates = getActivityScopeViewModel(StateHolder.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_shopping_cart, BR.vm, mStates);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);
        mBinding = (ActivityShoppingCartBinding) getBinding();

        mStates.titleBar.set("购物车");

        // 初始化视图
        initViews();
        // 初始化数据
        initData();
        // 设置监听器
        setupListeners();

        EventBus.getDefault().register(this);

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMsg event) {
        if ("refresh".equals(event.getMsg())) {
            mBinding.smartRefreshLayout.autoRefresh();
        }
    }


    private void initViews() {

        // 设置RecyclerView
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    public void onResume() {
        super.onResume();
        if (StringUtil.isEmpty(UserInfo.getInstance().getTokenValue())) {
            mBinding.smartRefreshLayout.autoRefresh();
        }
    }

    private void initData() {
        // 模拟数据，实际应用中应该从数据库或网络获取
        shops = new ArrayList<>();
        mAccountRequester.getCartList();
        mAccountRequester.getShopResult().observe(this, new Observer<ResponseStatus<Shop>>() {
            @Override
            public void onChanged(ResponseStatus<Shop> shopResponseStatus) {
                if (shopResponseStatus.getResponseCode() == 0) {
                    shops = shopResponseStatus.getData().getValidList();
                    adapter = new CartAdapter(ShoppingCartActivity.this, shops, ShoppingCartActivity.this);
                    mBinding.recyclerView.setAdapter(adapter);
                    updateTotalPrice();
                    if (shops.isEmpty()) {
                        mBinding.ivListNotData.setVisibility(VISIBLE);
                    } else
                        mBinding.ivListNotData.setVisibility(GONE);
                }
                mBinding.smartRefreshLayout.finishRefresh();
            }
        });
    }


    private List<Shop.ValidListBean> orderList = new ArrayList<>();

    private void setupListeners() {
        mBinding.checkboxSelectAll.setOnCheckedChangeListener((buttonView, isChecked) -> {
            adapter.selectAll(isChecked);
            updateTotalPrice();
        });

        mBinding.btnCheckout.setOnClickListener(v -> {
            if (adapter.getSelectedCount() == 0) {
                Toast.makeText(ShoppingCartActivity.this, "请选择商品", Toast.LENGTH_SHORT).show();
                return;
            }


            startActivity(new Intent()
                    .putParcelableArrayListExtra("data", (ArrayList<? extends Parcelable>) adapter.getShops())
                    .setClass(ShoppingCartActivity.this, ConfirmOrderActivity.class));
        });

        mBinding.smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initData();
            }
        });
    }

    private void updateTotalPrice() {
        double total = adapter.getTotalPrice();
        mBinding.totalPrice.setText(String.format("%.2f", total));
    }

    @Override
    public void onShopSelectedChanged(int shopPosition, boolean isSelected) {
        updateTotalPrice();
        updateSelectAllState();
    }

    @Override
    public void onItemSelectedChanged(int shopPosition, int itemPosition, boolean isSelected) {
        updateTotalPrice();
        updateSelectAllState();
    }

    @Override
    public void onQuantityChanged(int shopPosition, Shop.ValidListBean.SpecificationsBean itemPosition, int quantity) {

        mAccountRequester.cartUpdateCount(itemPosition.getId(), quantity);
        updateTotalPrice();
    }

    @Override
    public void onItemRemoved(int shopPosition, int itemPosition) {
        Shop.ValidListBean shop = shops.get(shopPosition);
        shop.getSpecifications().remove(itemPosition);

        // 如果店铺没有商品了，移除店铺
        if (shop.getSpecifications().isEmpty()) {
            shops.remove(shopPosition);
            adapter.notifyDataSetChanged();
        } else {
            adapter.notifyItemRemoved(itemPosition + shopPosition + 1);
        }

        updateTotalPrice();
        updateSelectAllState();
    }

    private void updateSelectAllState() {
        boolean allSelected = true;
        for (Shop.ValidListBean shop : shops) {
            if (!shop.isAllSelected()) {
                allSelected = false;
                break;
            }
        }
        mBinding.checkboxSelectAll.setChecked(allSelected);
    }

}
